/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "process.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define FPGA_ADDR 0x1a
#define FUNCTION_WRITE_MULTI_REG 0x10
#define FUNCTION_READ_MULTI_REG 0x03
#define DEVICE_TYPE	0x01	//TR
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
extern DMA_HandleTypeDef hdma_usart1_rx;;
extern DMA_HandleTypeDef hdma_uart4_rx;
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint32_t timecount = 0;
uint32_t timecount_1ms = 0;
uint32_t timecount_50ms = 0;
uint32_t timecount_500ms = 0;
uint32_t timecount_2000ms = 0;
uint32_t timecount_10000ms = 0;

uint8_t uDeviceFinish = 0;

uint8_t uDeviceType = DEVICE_TYPE;
uint8_t uDeviceAddr = 0;

uint8_t uart1RxBuf = 0;
uint8_t uart4RxBuf = 0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

static void devInit(void)
{
	static uint8_t tofpgaUart[8] = { 0 };
	uint16_t crc16 = 0x3a46;//fa03
	tofpgaUart[0] = 0x1a;
	tofpgaUart[1] = 0x03;
	tofpgaUart[2] = 0x00;
	tofpgaUart[3] = 0x00;
	tofpgaUart[4] = 0x00;
	tofpgaUart[5] = 0x24;
	//
	crc16 = calculateModbusCRC16(tofpgaUart,6);
	tofpgaUart[6] = (uint8_t)crc16&0xff;//crc16
	tofpgaUart[7] = (uint8_t)(crc16 >> 8)&0xff;//crc16
	HAL_UART_Transmit(&huart1, tofpgaUart, sizeof(tofpgaUart), 0xffff);
}


void system_process_1ms(void)
{
#if (USART1_IDE == 1)
	if(usart1RxFlag) {//获取设备ID
		if (FPGA_ADDR == usart1RxBuff[0] && FUNCTION_READ_MULTI_REG == usart1RxBuff[1]) {
			uDeviceAddr = usart1RxBuff[3];
			uDeviceFinish = 1;
		} else {
			uDeviceFinish = 0;
		}
		usart1RxLen = 0;
		usart1RxFlag = 0;

	}
#endif


#if (UART4_IDE == 1)
	if (uart4RxFlag) {//更新包数�???????????
		uint32_t i;
		len_state = 1 - len_state;
		HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, len_state);
		process_decode(uart4RxBuff,uart4RxLen);
		for(i=0;i<uart4RxLen;i++) {
			uart4RxBuff[i]=0;
		}
		HAL_Delay(50);
		printf("Receive Data(length = %d): \r\n",uart4RxLen);
		uart4RxLen=0;
		uart4RxFlag=0;
		HAL_UART_Receive_DMA(&huart4,uart4RxBuff,MAXBUFF);//再次�???????????????启DMA接收
	}
#endif


}

void system_process_50ms(void)
{
	if(timecount_50ms >= 50)
	{
		timecount_50ms = 0;

#if (USART1_IRQ == 1)
		if(usart1RxFlag)//获取设备ID
		{

			if (FPGA_ADDR == usart1RxBuff[0] && FUNCTION_READ_MULTI_REG == usart1RxBuff[1]) {
				uDeviceAddr = usart1RxBuff[3];
			} else {
				devInit();
			}
			usart1RxLen = 0;
			usart1RxFlag = 0;
		}
#endif

#if (UART4_IRQ == 1)
		if(uart4RxFlag)
		{
			uint32_t i;
			process_decode(uart4RxBuff,uart4RxLen);
			for(i=0;i<uart4RxLen;i++) {
				uart4RxBuff[i]=0;
			}
			uart4RxLen=0;
			uart4RxFlag=0;
		}
#endif
	}
}

void system_process_500ms(void)
{
	if (uDeviceFinish == 1)
	{
		timecount_500ms = 0;
	}
	if (timecount_500ms >= 500 )
	{
		devInit();
		timecount_500ms = 0;
	}
}

void system_process_2000ms(void)
{

	if(timecount_2000ms >= 2000)
	{
		printf("TR:%#x,boatload running..\r\n",uDeviceAddr);

		timecount_2000ms = 0;
	}
}

void system_process_10s(void)
{
	if(timecount_10000ms >= 10000)
	{
#if (DEBUG == 0)
		process_jump();
#endif
		timecount_10000ms = 0;
	}
}


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_UART4_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  uart4RxFlag = 0;
  uart4RxLen = 0;

#if (USART1_IDE == 1)
  __HAL_UART_ENABLE_IT(&huart1,UART_IT_IDLE); //使能空闲中断
  HAL_UART_Receive_DMA(&huart1,usart1RxBuff,FPGABUFF);//再次�???????????启DMA接收
#endif

#if (UART4_IDE == 1)
    __HAL_UART_ENABLE_IT(&huart4,UART_IT_IDLE); //使能空闲中断
    HAL_UART_Receive_DMA(&huart4,uart4RxBuff,MAXBUFF);//再次�????????????启DMA接收
#endif

#if (USART1_IRQ == 1)
  HAL_UART_Receive_IT(&huart1, &uart1RxBuf, 1);
#endif

#if (UART4_IRQ == 1)
  HAL_UART_Receive_IT(&huart4, &uart4RxBuf, 1);
#endif

  HAL_NVIC_DisableIRQ(DMA1_Channel1_IRQn);
  HAL_NVIC_DisableIRQ(DMA1_Channel2_IRQn);

  uDeviceFinish = 0; //TODO:2024-5-7 新增轮询读取FPGA ID标志位
  HAL_Delay(5000);//waiting FPGA
  devInit();

  timecount = 0;
  timecount_50ms = 0;
  timecount_500ms = 0;
  timecount_2000ms = 0;
  timecount_10000ms = 0;

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
	  if(timecount)
	  {
	  	timecount_50ms += timecount;
	  	timecount_500ms += timecount;
	  	timecount_2000ms += timecount;
	  	timecount_10000ms += timecount;


	  	system_process_1ms(); //ide

	  	system_process_50ms();//irq

	  	system_process_500ms();//irq

#if(DEBUG == 1)
	  	system_process_2000ms();//log
#endif

	  	system_process_10s();//jump

	  	timecount = 0;
	  }
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void UART_IDLECallBack(UART_HandleTypeDef *huart)
{
#if (USART1_IDE == 1)
	if(huart == &huart1) {
		HAL_UART_DMAStop(&huart1);
		usart1RxLen =  FPGABUFF - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx); //总计数减去未传输的数据个数，得到此次接收到的数据个数
		usart1RxFlag = 1;

		HAL_UART_Receive_DMA(&huart1,usart1RxBuff,FPGABUFF);//再次�???????????????启DMA接收
	}
#endif

#if (UART4_IDE == 1)
	if(huart == &huart4) {
		HAL_UART_DMAStop(&huart4);
		uart4RxLen =  MAXBUFF - __HAL_DMA_GET_COUNTER(&hdma_uart4_rx); //总计数减去未传输的数据个数，得到此次接收到的数据个数
		uart4RxFlag = 1;
	}
#endif

}


void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(huart);
  /* NOTE: This function Should not be modified, when the callback is needed,
           the HAL_UART_TxCpltCallback could be implemented in the user file
   */
#if (UART4_IRQ == 1)
  if(huart == &huart4) {

	if(uart4RxLen >= MAXBUFF)  //溢出判断
	{
		uart4RxFlag = 0;
		uart4RxLen = 0;
//		memset(uart4RxBuff,0x00,MAXBUFF);
	}
	else
	{
		uart4RxBuff[uart4RxLen++] = uart4RxBuf;
	}

	HAL_UART_Receive_IT(&huart4, &uart4RxBuf, 1);   //因为接收中断使用了一次即关闭，所以在�????后加入这行代码即可实现无限使�????
	uart4RxFlag = 1;
  }
#endif

#if (USART1_IRQ == 1)
  if(huart == &huart1) {

	if(usart1RxLen >= FPGABUFF)  //溢出判断
	{
		usart1RxFlag = 0;
		usart1RxLen = 0;
	}
	else
	{
		usart1RxBuff[usart1RxLen++] = uart1RxBuf;
	}

	HAL_UART_Receive_IT(&huart1, &uart1RxBuf, 1);   //因为接收中断使用了一次即关闭，所以在�????后加入这行代码即可实现无限使�????
	usart1RxFlag = 1;
  }
#endif

  timecount_50ms = 0;
}



/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
